<?php
namespace app\mobile\controller;

use app\mobile\model\State;
use think\Db;
use app\common\traits\Page;
use app\common\model\Order;
use app\common\model\Order_log;
use think\Request;
use app\common\traits\Gate;
use app\common\model\Leibie;
use \think\View;
use app\admin\model\Dq;
use app\common\common;
use think\Facade\Session;
use think\helper\Time;

use Carbon\Carbon;
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/10
 * Time: 10:54
 */
class Index extends Mobile
{
    use Page;
    use Gate;
    public function index($id=0)
    {
        $depar_id=session('admin_user.depar_id');
        $depar=Db::name('Depar')->where("status=1 and id=$depar_id")->value('name');

        $mobile_id=model('auth_rule')->field('id')->where('mstatus=1')->column('title','id');
        $intersection = array_intersect(array_keys($mobile_id), $this->auth_ids_list);
        $data = Db::name('AuthRule')->where(['id'=>['in',$intersection]])->select();
        $this->assign('depar',$depar);
        $this->assign('list',$data);

        //渠道经理、渠道主管、网络经理、网络主管、邀约经理、邀约主管、活动经理、活动主管
        if($this->hasRole('qudaojingli')  || $this->hasRole('wangluojingli') || $this->hasRole('yaoyuejingli')  || $this->hasRole('huodongjingli') ) {
            $this->assign('position', '经理');
        }elseif($this->hasRole('qudaozhuguan')|| $this->hasRole('wangluozhuguan') || $this->hasRole('yaoyuezhuguan') || $this->hasRole('huodongzhuguan')){
            $this->assign('position', '主管');
        }elseif( $this->hasRole('qudaozhuanyuan') || $this->hasRole('wangluozhuanyuan') ||$this->hasRole('yaoyuezhuanyuan')||$this->hasRole('huodongzhuanyuan')) { //渠道专员、网络专员//邀约专员、活动
            $this->assign('position', '专员');
        }elseif($this->hasRole('sheyingdiaodu')){
            $this->assign('position', '调度');
        }
        $juese=model('Users')->where('id',session('admin_user.adminid'))->find();
        $this->assign('juese',$juese);
        return $this->fetch();
    }

    public function search(Request $request)
    {
        $map = $request->param();
        if(!empty($map['number'])){

            $select=Order::where(['id|maphone|otherphone'=>$map['number'],'status'=>1])->count();
            if($select>0){
                $select_re=Order::where(['id|maphone|otherphone'=>$map['number'],'status'=>1])->limit(1)->select();
                $condition=[1,2,3,4,5,6,7,9];
                $data = doData($select_re,$condition);//halt($data);
                $this->assign('list',$data);
            }else{
                $this->assign('s','9');
                $this->assign('list','noselect');
            }
        }else{
            $this->assign('list','noselect');
        }

        $this->assign('search',$map['number']);
        return $this->fetch('search');
    }

    public  function  add_list(){
        $order = new Order();
        if($this->request->isPost()) {
            $data = $this->request->post();

//            $data['jdtime'] = time();
//            $data['cztime'] = time();
//            $data['status'] = 1;  //订单启用group_id
//            $user = session('admin_user');
//            $data['jdry']   = $user['adminid'];//建单人员
//            $data['qd_depar']   = $user['depar_id'];//建单人员部门
//            $data['group_id']=$user['group_id'];//活动会所地址id
//            if($user['depar_id']==3){
//                $data['yykf']=$user['adminid'];//邀约人员
//            }

            $re = $order->edit($data,$khd=2);//成功返回1
            return json($re);
        }else{
            $state=State::all();
            $leibie = new Leibie();
            $area = $leibie->getArea();
            //dump($area);exit;
            $this->getSj();
            $hsjd=input('fkry');
            $this->assign('hsjd',$hsjd);
            $this->assign('area',$area);
            $this->assign('state',$state);
            return $this->fetch('add_list');
        }
    }


    //是否建单
    public function jiandan(){
        $this->redirect('index/add_list');
    }
    /*  新增或修改订单  */
    public function edit(){
//        $order = new Order();
//        $quanxian = $order->getQuanxian();
        $quanxian = $this->getQuanxian();
        $getqx = $quanxian['status'];
        if($getqx == 1){
            $order = new Order();
            $id = $this->request->param('id');
            if($this->request->isPost()){
                $data = $this->request->post();
                $re = $order->edit($data,$khd=2);//成功返回1
                return $re;
            }else{
                $map['id'] = $id;
                $info = $order->where($map)->find();
                if($info['ywstate']!=1){
                    if($this->hasRole('qudaojingli') || $this->hasRole('qudaozhuguan') || $this->hasRole('wangluojingli') || $this->hasRole('wangluozhuguan')){
                        $info = $this->protectData($info);//加密
                    }
                }
                $this->getSj();
                if( $this->hasRole(['qudaozhuguan','wangluozhuguan','yaoyuezhuguan','qudaozhuanyuan','wangluozhuanyuan','yaoyuezhuanyuan']) ){
                    $this->assign('zgzy',1);//主管专员
                }else{
                    $this->assign('zgzy',0);
                }
                if($this->hasRole('yaoyuezhuanyuan')){//邀约专员
                    $this->assign('yaozy',1);
                }else{
                    $this->assign('yaozy',0);
                }
                if($this->hasRole(['qudaozhuguan','qudaozhuanyuan'])){//渠道主管，专员不能修改医院信息
                    $this->assign('disyiyuan',1);
                }
                $this->assign('info',$info);//输出
                return $this->getEditMoban();// 页面模板
            }
        }elseif ($getqx == 2){
            $this->error("{$quanxian['msg']}");
        }else{
            $this->error('您没有权限！');
        }

    }

    //权限
    public function getQuanxian(){
        $order  = new Order();
        $quanxian = $order->getQuanxian();
        return $quanxian;
    }
    public function listing(Request $request)
    {
        $order = new Order();
        $map = $request->param();
        if(!empty($map['editid'])){
            $mapa = session('map');
            $map  = array_merge($mapa,['p'=>$map['p']]);
            $map = session('map',$map);
        }else{
            $map = session('map',$map);
        }
        $map = session('map');
        $this->assign('form',$map);

        $data = $order->maps($map);
        $list = $this->pageshow('order',$data);
        $list = $this->protectData($list);//加密
//        if($list['ywstate'] !=1 ){
//            if($this->hasRole('qudaojingli') || $this->hasRole('qudaozhuguan') || $this->hasRole('wangluojingli') || $this->hasRole('wangluozhuguan')){
//                $list = $this->protectData($list);//加密
//            }
//        }
        $this->assign('list',$list);
        $this->getSj();
        return $this->fetch('listing');
    }

    //今日追踪
    public function today_zhuizong(){
        $this->redirect('index/listing', ['today_xinxi' => 'today_zhuizong']);
    }

    //今日邀约拍摄
    public function today_yaoyuepaishe(){
        $this->redirect('index/listing', ['today_xinxi' => 'today_yaoyuechenggong']);
    }
    //今日报名课程
    public function today_baomingkecheng(){
        $this->redirect('index/listing', ['today_xinxi' => 'today_baomingkecheng']);
    }
    //今日取消拍摄
    public function today_quxiaopaishe(){
        $this->redirect('index/listing', ['today_xinxi' => 'today_quxiaopaishe']);
    }
    //今日拍摄成功
    public function today_paishechenggong(){
        $this->redirect('index/listing', ['today_xinxi' => 'today_paishechenggong']);
    }
    //今日分配订单
    public function today_fenpeidingdan(){
        $this->redirect('index/listing', ['today_xinxi' => 'today_fenpeidingdan']);
    }
    /*今日拍摄
    * */
    public function today_paishe(){
        $this->redirect('index/listing', ['today_xinxi' => 'today_paishe']);
    }
    //今日分配
    public function today_fenpei(){
        $this->redirect('index/listing', ['today_xinxi' => 'today_fenpei']);
    }
    //今日报名
    public function today_baoming(){
        $this->redirect('index/listing', ['today_xinxi' => 'today_baoming']);
    }
    //今日取消报名
    public function today_quxiaobaoming(){
        $this->redirect('index/listing', ['today_xinxi' => 'today_quxiaobaoming']);
    }
    //今日未到
    public function today_weidao(){
        $this->redirect('index/listing', ['today_xinxi' => 'today_weidao']);
    }
    //预约今日拍摄
    public function today_yuyuepaishe(){
        $this->redirect('index/listing', ['today_xinxi' => 'today_yuyuepaishe']);
    }
    //今日反馈
    public function today_fankui(){
        $this->redirect('index/listing', ['today_xinxi' => 'today_fankui']);
    }


    /**分配
     * @return mixed
     */
    public function fenpei_dingdan(){
//        $this->redirect('index/fenpei', ['act' =>'1']);
        $order = new Order();
        $data = $this->request->param();
        if($this->request->isPost()){
            return $order->fenpeiZy($data,2);
        }else{
            $data = action('admin/yewu/fenpei_Common_Data',$data);
//            $data = $this->fenpei_Common_Data($data);
            if(!empty($data['ywstate'])){
                $data['ywstate'] = $data['ywstate'];
            }else{
                $data['ywstate'] = ['in',[1,4,7]];
            }
            $data['yykf'] = ['eq',0];//邀约客服为空
            $data['qd_depar'] = ['neq',3];//来电单不分配
            $data['id'] = ['notbetween',[15461,16020]];
            $list = $this->pageshow('order',$data);
            $this->assign('list',$list);
            return $this->fetch('fenpei_dingdan');
        }
    }
    //分配会所
    public function fenpei_huisuo(){
//        $this->redirect('index/fenpei', ['act' =>'2']);
        $order = new Order();
        $data = $this->request->param();
        if($this->request->isPost()){
            return $order->fenpeiHs($data,2);
        }else{
            $data = action('admin/yewu/fenpei_Common_Data',$data);
//            $data = $this->fenpei_Common_Data($data);
            $data['hsdzid']  = ['eq',0];//会所门店为空
            $list = $this->pageshow('order',$data,'','','id desc',15);
            $this->assign('list',$list);
            return $this->fetch('fenpei_huisuo');
        }
    }

    //微信推送
    public function pushweixin(){
        if($this->hasRole(['sheyingdiaodu','sheyingjingli'])){
            return ['msg'=>"您没有权限",'status'=>0,'icon'=>2,'url'=>url('listing')];
        }else{
            $id = $this->request->param('id');
            return ['msg'=>"恭喜您有权限",'status'=>1,'icon'=>1,'url'=>url('weixin',['id'=>$id])];
        }
    }
    public function weixin(){
        $order=new order();
        if($this->request->isPost()){
            $data = $this->request->param();
            if( $this->hasRole(["qudaojingli","qudaozhuguan","qudaozhuanyuan","wangluojingli","wangluozhuguan","wangluozhuanyuan"]) ){
                $data['qdbz'] = $data['bz'];
            }elseif( $this->hasRole(["yaoyuejingli","yaoyuezhuguan","yaoyuezhuanyuan"]) ){
                $data['yybz'] = $data['bz'];
            }elseif (  $this->hasRole(["huodongjingli","huodongzhuguan","huodongzhuanyuan"]) ){
                $data['hsbz'] = $data['bz'];
            }else{
                $data['qdbz'] = $data['bz'];
            }
            unset($data['bz']);

            $olddata = $order->where('id', $data['id'])->find();

//            if( ($olddata['ywstate'] != 1 && $olddata['ywstate'] != 4)  && $data['ywstate'] == 7  && $this->hasRole(['qudaojingli','qudaozhuguan','qudaozhuanyuan','wangluojingli','wangluozhuguan','wangluozhuanyuan','huodongjingli','huodongzhuguan',huodongzhuanyuan])){
//                $ywstate = $data['ywstate'];
//                unset($data['ywstate']);
//            }

            if($data['ywstate'] == 7 &&$this->hasRole(['qudaojingli','qudaozhuguan','qudaozhuanyuan','wangluojingli','wangluozhuguan','wangluozhuanyuan','huodongjingli','huodongzhuguan','huodongzhuanyuan']) ){
                if($olddata['ywstate'] == 5 || $olddata['ywstate'] == 6){
                    return ['msg'=>"该客人已预约或拍摄，不能反馈",'status'=>2,'icon'=>4,'url'=>url('search')];
                }
                $data['fkbm'] = session('admin_user.depar_id');//反馈部门
                $data['fkry'] = session('admin_user.adminid');//反馈人员
                $data['fktime'] = time();
                if( $olddata['ywstate'] != 1 && $olddata['ywstate'] != 4 ){
                    $ywstate = $data['ywstate'];
                    unset($data['ywstate']);
                }
            }

            $data = $order->editData($data,$olddata);
            $result = $order->allowField(true)->isUpdate()->save($data);
            if($result){
                if( ($olddata['ywstate'] != 1 && $olddata['ywstate'] != 4) && $ywstate == 7 && $this->hasRole(['qudaojingli','qudaozhuguan','qudaozhuanyuan','wangluojingli','wangluozhuguan','wangluozhuanyuan','huodongjingli','huodongzhuguan',huodongzhuanyuan])){
                    $data['ywstate'] =  $olddata['ywstate'];
                }else{
                    $ywstate = $data['ywstate'];
                }
                if($ywstate == 7){
                    $data['operation'] = 6;//意向反馈
                }else{
                    $data['operation'] = 8;//邀约拍摄
                }
                $order_log = new Order_log();
                $order_log->log($data,2);

                $res = $order->weixin($data,$ywstate);
                if($res['status'] == 1){
                    $res['url'] = url('listing');
                }else{
                    $res['url'] = url('pushweixin',['orderid'=>$data['id']]);
                }
                return $res;
            }
        }else{
            if ($this->hasRole(['yaoyuejingli','yaoyuezhuguan','yaoyuezhuanyuan'])){
                $this->assign('yaoyue',1);
            }else{
                $this->assign('yaoyue',0);
            }
            $states = $this->checkState();//每个角色的特定状态
            $this->getSj();
            $this->assign('states',$states);
            $id = $this->request->param('id');

            $info = $order->where(['id'=>$id])->find();
            if( $this->hasRole(['qudaojingli','qudaozhuguan','qudaozhuanyuan','wangluojingli','wangluozhuguan','wangluozhuanyuan']) ){
                $bz = $info['qdbz'];
            }elseif( $this->hasRole(['yaoyuejingli','yaoyuezhuguan','yaoyuezhuanyuan']) ){
                $bz = $info['yybz'];
            }elseif( $this->hasRole(['huodongjingli','huodongzhuguan','huodongzhuanyuan']) ){
                $bz = $info['hsbz'];
            }
            $this->assign('bz',$bz);//备注
            $this->assign('info',$info);//输出
            return $this->fetch('weixin');
        }
    }
    public function zjsshenhe(){
        $id = input('id');
        $this->assign('editid',empty($id)?0:$id);

        $ordersinfo = Db::name('orders')->field('a.*,d.username,d.mobile')->where(['a.status'=>2])->alias('a')->join('customer d','a.user_id = d.id')->select();
        $this->assign('list',$ordersinfo);
        $depar = Db::name('customer')->select();
        $this->assign('user',$depar);
        return $this->fetch();
    }

    //手机端简报
    public function jianbao(){
        $order = new Order();
        $uid = session('admin_user.adminid');
        $search = request()->param();
        $time = empty($search['time'])? Time::today():time_StrToArr($search['time']) ;

        if( $this->hasRole('yaoyuezhuanyuan',$uid ) ){
            $data = $order->zhuanyuan_Jianbao($time,$uid,1);
            $jingli = 3;
        } elseif( $this->hasRole("yaoyuezhuguan",$uid ) ){
            $yg = Db::name('users')->where(['status'=>1,'id'=>$uid])->field('ygroup_id')->find();
            $ygroup = $yg['ygroup_id'];
            if( !empty($search['yykf']) ){
                $data = $order->zhuanyuan_Jianbao($time,$search['yykf'],1);
            }else{
                $data = $order->zhuguan_Jianbao($time,$ygroup,1);
            }
            $search['ygroup'] = $ygroup;
            $jingli = 2;
        }else{
            if( !empty($search['yykf']) ){
                $data = $order->zhuanyuan_Jianbao($time,$search['yykf'],1);
            }elseif( !empty($search['ygroup'] )){
                $data = $order->zhuguan_Jianbao($time,$search['ygroup'],1);
            }else{
                $data = $order->jingli_Jianbao($time,1);
            }
            $jingli = 1;
        }
        $ygroup = $this->getYgroup();
        $yykf = $this->getYykf($search['ygroup']);
        return view("jianbao", [ 'data' => $data,'jingli'=>$jingli,'ygroup'=>$ygroup,'yykf'=>$yykf,'search'=>$search]);
    }

    //手机端获取医院详细
    public function yiyuan_Detail()
    {
        $search_time = request()->param('time');
        $time = empty($search_time)?Time::today():time_StrToArr($search_time);
        $leibie = new Leibie();
        $area = $leibie->getArea();
        $datas = collect(Db::name('order')->where(['status' => 1, 'qd_depar' => 1, 'jdtime' => ['between', $time] ])->field('id,area,yiyuan')->select());
        foreach ($area as $val) {
            $data[$val['id']]['area_name'] = $val['name'];
            $data[$val['id']]['area_num'] = $datas->where('area',$val['id'])->count();
            $yiyuanInfo = $leibie->getYiyuan($val['id']);
            foreach ($yiyuanInfo as $v) {
                $data[$val['id']]['yiyuan'][$v['id']]['yiyuan_name'] = $v['name'];
                $data[$val['id']]['yiyuan'][$v['id']]['yiyuan_num'] = $datas->where('yiyuan',$v['id'])->count();
            }
        }
        unset($datas);
        return view("yiyuan_detail", [ 'data' => $data,'time'=>$search_time]);
    }

    //获取邀约分组
    public function getYgroup(){
        return Db::name('ygroup')->where(['status'=>1,'depar_id'=>3])->field('id,group_name')->select();
    }
    //获取邀约客服
    public function getYykf($ygroup_id = ''){
        if(empty($ygroup_id)){
            return Db::name('users')->where(['status'=>1,'depar_id'=>3])->field('id,username')->select();
        }else{
            return Db::name('users')->where(['status'=>1,'depar_id'=>3,'ygroup_id'=>$ygroup_id])->field('id,username')->select();
        }
    }

    /**
     * 渠道简报
     */
    public function qudaojianbao(){
        $search = $this->request->param();
        $this->assign('search',$search);
        if(!empty($search['jdtime'])){
            $jdtime = Carbon::parse($search['jdtime']);
            $map['jdtime'] = ['between',[strtotime($jdtime->startOfMonth()->toDateTimeString()), strtotime($jdtime->endOfMonth()->toDateTimeString())]];
        }
        if(!empty($search['yctime'])){
            $yctime = Carbon::parse($search['yctime']);
            $map['yctime'] = ['between',[strtotime($yctime->startOfMonth()->toDateTimeString()), strtotime($yctime->endOfMonth()->toDateTimeString())]];
        }
        if(empty($search['jdtime']) && empty($search['yctime']) ){
            $yctime = Carbon::now();
            $map['yctime'] = ['between',[strtotime($yctime->startOfMonth()->toDateTimeString()), strtotime($yctime->endOfMonth()->toDateTimeString())]];
        }
        $leibie = new Leibie();
        $area = $leibie->getArea();
        $map['status'] = 1;
        $map['qd_depar'] = 1;
        $datas = collect(Db::name('order')->where($map)->field('id,area,yiyuan')->select());
        foreach ($area as $val) {
            $data[$val['id']]['area_name'] = $val['name'];
            $data[$val['id']]['area_num'] = $datas->where('area',$val['id'])->count();
            $yiyuanInfo = $leibie->getYiyuan($val['id']);
            foreach ($yiyuanInfo as $v) {
                $data[$val['id']]['yiyuan'][$v['id']]['yiyuan_name'] = $v['name'];
                $data[$val['id']]['yiyuan'][$v['id']]['yiyuan_num'] = $datas->where('area',$val['id'])->where('yiyuan',$v['id'])->count();
            }
        }
        $this->assign('data',$data);
        unset($datas);
        return $this->fetch('qudaojianbao');
    }


}